package senzuri.acceleraudio.data;

import android.database.Cursor;

import java.util.Arrays;
import java.util.Date;

public class MusicSession implements Comparable<MusicSession> {
  public final int id;
  public final Date created;
  public final int data;
  public String name;
  public Date modified;
  public Parameters parameters;
  
  public MusicSession(Cursor cursor) {
    this.id = cursor.getInt(0);
    this.name = cursor.getString(cursor.getColumnIndex("name"));
    this.created = new Date(cursor.getLong(cursor.getColumnIndex("created")));
    this.modified = new Date(cursor.getLong(cursor.getColumnIndex("modified")));
    this.parameters = new Parameters(cursor.getString(cursor.getColumnIndex("parameters")));
    this.data = cursor.getInt(cursor.getColumnIndex("data"));
  }
  
  public static class Parameters {
    private static final int[] allowedSamplingRates = new int[] {
      8000, 11025, 22050, 44100, 48000, 96000 };
    public boolean useMicrophone;
    public boolean useAccelerometerX;
    public boolean useAccelerometerY;
    public boolean useAccelerometerZ;
    public boolean useGPS;
    public int samplingRate;
    
    public Parameters(String serialized) {
      if (serialized.length() < 6)
        serialized += "000000";
      useAccelerometerX = serialized.charAt(0) == '1';
      useAccelerometerY = serialized.charAt(1) == '1';
      useAccelerometerZ = serialized.charAt(2) == '1';
      useGPS = serialized.charAt(3) == '1';
      useMicrophone = serialized.charAt(4) == '1';
      samplingRate = allowedSamplingRates[serialized.charAt(5) - '0'];
    }
    
    public String serialize() {
      int samplingRateIndex = Arrays.binarySearch(allowedSamplingRates, samplingRate);
      if (samplingRateIndex < 0)
        throw new IndexOutOfBoundsException("samplingRate has an invalid value");
      
      return
          (useAccelerometerX ? "1" : "0") +
          (useAccelerometerY ? "1" : "0") +
          (useAccelerometerZ ? "1" : "0") +
          (useGPS ? "1" : "0") +
          (useMicrophone ? "1" : "0") +
          (char)((int)'0' + samplingRateIndex);
    }
    
    public boolean useAccelerometer() {
      return useAccelerometerX || useAccelerometerY || useAccelerometerZ;
    }
    
    @Override public boolean equals(Object o) {
      if (o == null)
        return false;
      if (o instanceof Parameters) {
        Parameters other = (Parameters) o;
        return other.serialize().equals(serialize());
      }
      return super.equals(o);
    }
  }

  @Override public int compareTo(MusicSession another) {
    if (this.data == another.data)
      return this.id - another.id;
    return this.data - another.data;
  }
}
